package com.example.perftool2;

import android.app.ActivityManager;
import android.os.Debug;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class MemTool {

    private static final String TAG = "MemTool";

    public long[] getMemoryUsage(ActivityManager activityManager, int[] pids) {
        try {
            Debug.MemoryInfo[] memoryInfos = activityManager.getProcessMemoryInfo(pids);
            long[] rets = new long[memoryInfos.length];
            for (int i = 0; i < memoryInfos.length; i++) {
                rets[i] = memoryInfos[i].getTotalPss() /*kB*/ * 1024L;// rets 元素的单位是B
            }
            return rets;
        } catch (Exception e) {
            Log.e(TAG, "Failed to get memory usage", e);
            return null;
        }
    }

    public String getTotalFreeMem() {
        return execShellForFreeMem();
    }

    public static final String COMMAND_EXIT = "exit\n";
    public static final String COMMAND_LINE_END = "\n";

    private String execShellForFreeMem() {
        String freeRam = "";

        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = null;
        StringBuilder errorMsg = null;

        DataOutputStream os = null;
        try {
            process = Runtime.getRuntime().exec("sh");
            os = new DataOutputStream(process.getOutputStream());
            os.write("dumpsys meminfo".getBytes());
            os.writeBytes(COMMAND_LINE_END);
            os.flush();
            os.writeBytes(COMMAND_EXIT);
            os.flush();
            process.waitFor();

            successResult = new BufferedReader(new InputStreamReader(
                    process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(
                    process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                if (!TextUtils.isEmpty(s) && s.contains("Free RAM:")) {
                    String[] strings = s.split(" ");
                    boolean passRam = false;
                    for(String s1 : strings) {
                        if (!TextUtils.isEmpty(s1) && s1.contains("RAM")) {
                            passRam = true;
                            continue;
                        }
                        if (passRam && !TextUtils.isEmpty(s1) && s1.contains("K")) {
                            freeRam = s1;
                            freeRam = freeRam.replace(",", "_");
                            break;
                        }
                    }
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (process != null) {
                process.destroy();
            }
        }
        return freeRam;
    }
}
